<?php

/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/3/16
 * Time: 13:40
 */
namespace Bbs\Api;

use Bbs\Model\ForumAdmingroupModel;
use Bbs\Model\ForumPostModel;
use Common\Api\Api;

class ForumPostApi extends Api{

    /**
     * 添加
     */
    const ADD = "Bbs/ForumPost/add";
    /**
     * 保存
     */
    const SAVE = "Bbs/ForumPost/save";
    const COUNT = "Bbs/ForumPost/count";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Bbs/ForumPost/saveByID";

    /**
     * 删除
     */
    const DELETE = "Bbs/ForumPost/delete";

    /**
     * 查询
     */
    const QUERY = "Bbs/ForumPost/query";
    const QUERY_NO_PAGING = "Bbs/ForumPost/queryNoPaging";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Bbs/ForumPost/getInfo";


    const QUERY_WITH_COUNT = "Bbs/ForumPost/queryWithCount";

    const QUERY_WITH_THREAD ="Bbs/ForumPost/queryWithThread";

    /**
     * 帖子查询
     */
    const QUERY_POST = "Bbs/ForumPost/queryPost";

    /**
     * 帖子详情
     */
    const DETAIL_POST = "Bbs/ForumPost/detailPost";

    /**
     * 评论查询
     */
    const QUERY_COMMENT = "Bbs/ForumPost/commentQuery";
    const QUERY_ALL_POST2 = "Bbs/ForumPost/queryAllPost2";

    /**
     * 主题回帖
     */
    const REPLY = "Bbs/ForumPost/reply";

    /**
     * 删除帖子
     */
    const DELETE_POST = "Bbs/ForumPost/deletePost";

    /**
     * 删除评论
     */
    const DELETE_COMMENT = "Bbs/ForumPost/deleteComment";

    /**
     * 帖子评论
     */
    const REPLY_POST = "Bbs/ForumPost/replyPost";

    protected function _init(){
        $this -> model = new ForumPostModel();
    }


    public function queryWithThread($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){

        $query = $this -> model -> join("itboye_forum_thread on itboye_forum_post.tid=itboye_forum_thread.tid","left");

        $query = $query -> page($page['curpage'] . ',' . $page['size']);

        if(!is_null($map)){
            $query = $query -> where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> join("itboye_forum_thread on itboye_forum_post.tid=itboye_forum_thread.tid","left") -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("count" => $count, "list" => $list));

    }


    /**
     * 帖子查询
     * @param $fid
     * @param $tid
     * @param $typeid
     * @param $curpage
     * @param $pagesize
     * @param $maxcomment
     * @param $view_inc
     * @return array
     */
    public function queryPost($fid,$tid,$typeid,$curpage,$pagesize,$maxcomment,$view_inc){
        $curpage = intval($curpage);
        $pagesize = intval($pagesize);

        $maxcomment = intval($maxcomment);

        if($curpage < 1){
            $curpage = 1;
        }
        if($pagesize > 30){
            $pagesize = 30;
        }
        if($pagesize <= 0){
            $pagesize = 10;
        }

        if($maxcomment < 2){
            $maxcomment = 2;
        }
        if($maxcomment>10){
            $maxcomment = 10;
        }

        if(in_array($tid,array('rrasj','fxphb'))){
            $fid = 0;
        }

        //判断论坛是否开启帖子审核
        $modnewposts = 0;
        if($fid !=0){
            $result = apiCall(ForumForumApi::GET_INFO,array(array('fid'=>$fid)));
            if($result['status']){
                if(is_null($result['info'])){
                    return $this->apiReturnErr('论坛ID无效');
                }else{
                    $modnewposts = $result['info']['modnewposts'];
                }
            }else{
                return $this->apiReturnErr('查询失败');
            }
        }else{

            if($tid == 'rrasj'){
                $tid = 6068;  //人人爱设计
            }
            if($tid == 'fxphb'){
                $tid = 6067; //疯享排行榜
            }

        }

        $map = array(
            'fid' => $fid,
            'tid' => $tid,
            'typeid' => $typeid,
            'status' => 1,
        );

        if($modnewposts == 1){
            //需要审核
            $map['invisible'] = 1;
        }

        $page = array('curpage'=>$curpage,'size'=>$pagesize);
        $order['position'] = 'asc';

        $result = apiCall(ForumPostApi::QUERY_WITH_COUNT,array($map,$page,$order));

        if($result['status']){
            $info = $result['info'];
            if(!is_null($info['list'])){

                foreach($info['list'] as &$val){
                    //时间转换
                    $val['dateline_show'] = date("Y-m-d H:i:s",$val['dateline']);

                    //查询用户信息
                    $this->getUserInfo($val['author_id'],$val);

                    //查询附件
                    $this->queryAttachment($tid,$val['pid'],$val);

                    //查询评论
                    $this->queryComments($tid,$val['pid'],$maxcomment,$val);

                }

            }
            //查看次数加1
            if($view_inc==1){
                $map = array(
                    'tid' => $tid
                );
                apiCall(ForumThreadApi::SET_INC,array($map,'views'));
            }

            return $this->apiReturnSuc($info);

        }else{
            return $this->apiReturnErr('查询失败');
        }
    }

    /**
     * 帖子详情
     * @param $fid
     * @param $tid
     * @param $pid
     */
    public function detailPost($fid,$tid,$pid){
        $map = array(
            'fid' => $fid,
            'tid' => $tid,
            'pid' => $pid
        );
        $result = apiCall(ForumPostApi::GET_INFO,array($map));
        if($result['status']){
            $info = $result['info'];
            $map = array(
                'fid' => $fid,
                'tid' => $tid
            );
            $result = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,array('aid')));
            if($result['status']){
                //时间转换
                $info['dateline_show'] = date("Y-m-d H:i:s",$info['dateline']);

                //查询用户信息
                $this->getUserInfo($info['author_id'],$info);

                //查询附件
                $this->queryAttachment($fid,$tid,$info);

                //查询评论
                $this->queryComments($tid,$info['pid'],$maxcomment,$info);

            }

            return $this->apiReturnSuc($info);
        }else{
            return $this->apiReturnErr('查询失败');
        }
    }

    /**
     * 评论查询
     * @param $tid
     * @param $pid
     * @param $curpage
     * @param $pagesize
     * @param $curpage
     * @param $pagesize
     * @return array
     */
    public function commentQuery($tid,$pid,$curpage,$pagesize){

        $curpage = intval($curpage);
        $pagesize = intval($pagesize);

        if($curpage < 1){
            $curpage = 1;
        }
        if($pagesize > 30){
            $pagesize = 30;
        }
        if($pagesize <= 0){
            $pagesize = 10;
        }

        $map = array(
            'tid' => $tid,
            'pid' => $pid
        );

        $page = array('curpage'=>$curpage,'size'=>$pagesize);
        $order['id'] = 'desc';

        $result = apiCall(ForumPostcommentApi::QUERY_WITH_COUNT,array($map,$page,$order));

        if($result['status']){
            foreach($result['info']['list'] as &$val){
                //时间转换
                $val['dateline_show'] = date("Y-m-d H:i:s",$val['dateline']);
                //查询用户信息
                $this->getUserInfo($val['author_id'],$val);
            }

            return $this->apiReturnSuc($result['info']);
        }else{
            return $this->apiReturnErr('查询失败');
        }

    }

    public function reply($fid,$tid,$author,$author_id,$subject,$message,$attachments){

        $useip = 0;
        if(!empty($_SERVER['REMOTE_ADDR'])){
            $useip = $_SERVER['REMOTE_ADDR'];
        }

        //验证用户权限
        $result = apiCall(ForumUserAdmingroupApi::POWER,array($author_id));
        if($result['status']){
            $power = $result['info'];
            if(is_array($power)){
                if($power[ForumAdmingroupModel::ALLOW_POST] == 0 && ($power['fid'] == $fid || $power['fid'] == 0)){
                    return $this -> apiReturnErr("无回帖权限");
                }
            }
        }else{
            return $this -> apiReturnErr($result['info']);
        }

        //查询帖子楼层
        $map = array(
            'tid' => $tid,
            'fid' => $fid
        );
        $order['pid'] = 'desc';
        $model = new ForumPostModel();

        $result = $model->where($map)->order($order)->lock(true)->find();

        $position = 0;

        if($result!==false){
            if($result==null){
                return $this->apiReturnErr('出错，没有1楼');
            }else{
                $position = $result['position'] + 1;


                //主题回复数+1
                $map = array(
                    'tid' => $tid
                );
                $result = apiCall(ForumThreadApi::SET_INC,array($map,'replies'));
                if(!$result['status']){
                    return $this->apiReturnErr('回帖失败');
                }
                //论坛回复数+1
                $map = array(
                    'fid' => $fid
                );
                $result = apiCall("Bbs/ForumForum/setInc",array($map,'posts'));
            }
        }else{
            return $this->apiReturnErr('回帖失败');
        }


        $entity = array(
            'author' => $author,
            'author_id' => $author_id,
            'subject' => $subject,
            'dateline' => time(),
            'message' => $message,
            'useip' => ip2long($useip),
            'invisible' => 0,
            'status' => 1,
            'comment' => 0,
            'position' => $position,
            'tid' => $tid,
            'fid' => $fid
        );

        $result = $model->lock(false)->add($entity);

        $pid = $result;

        if($result!==false){

            //添加附件
            if($attachments !== ""){
                $aid = explode(',',$attachments);
                $dataList = array();
                $i = 0;
                if(count($aid) >6){
                    $aid = array_slice($aid,0,6);
                }
                foreach($aid as $v){
                    $dataList[$i] = array(
                        'tid' => $tid,
                        'pid' => $pid,
                        'uid' => $author_id,
                        'aid' => $v,
                    );
                    $i++;
                }
                $result = apiCall(ForumAttachmentApi::ADD_ALL,array($dataList));
            }
            if(!$result['status']){
                return $this -> apiReturnErr($result['info']);
            }

            return $this->apiReturnSuc($result);
        }else{
            return $this->apiReturnErr('回帖失败');
        }
    }


    /**
     * 删除帖子
     * @param $uid
     * @param $fid
     * @param $tid
     * @param $pid
     * @return array
     */
    public function deletePost($uid,$fid,$tid,$pid){

        $map = array(
            'fid' => $fid,
            'tid' => $tid,
            'pid' => $pid
        );


        $result = apiCall(ForumPostApi::GET_INFO,array($map));

        //查询该帖子
        if($result['status']){
            if(is_null($result['info'])){
                return $this->apiReturnErr('指定帖子不存在');
            }else{
                $post_info = $result['info'];
                if($post_info['status']==0){
                   return $this->apiReturnErr('指定帖子已删除');
                }
            }
        }else{
            return $this->apiReturnErr('删除失败');
        }


        if($post_info['author_id']==$uid){
            //作者可以删除自己的帖子
            $result = apiCall(ForumPostApi::SAVE,array($map,array('status'=>0)));

        }else{

            //判断是否有管理员的删帖权限
            $result = apiCall(ForumUserAdmingroupApi::DELETE_POST,array($uid,$fid,$tid,$pid));

        }

        if($result['status']){

            //主题回复数-1
            $map = array(
                'tid' => $tid
            );
            $result = apiCall(ForumThreadApi::SET_DEC,array($map,'replies',1));

            //论坛回复数+1
            $map = array(
                'fid' => $fid
            );
            $result = apiCall("Bbs/ForumForum/setDec",array($map,'posts',1));

            return $this->apiReturnSuc('删除成功');
        }else{
            return $this->apiReturnErr('删除失败');
        }

    }


    public function deleteComment($uid,$tid,$pid,$id){

        //获取帖子信息，帖子主人以及评论者可删除
        $map = array(
            'tid' => $tid,
            'pid' => $pid
        );

        $result = apiCall(ForumPostApi::GET_INFO,array($map));

        if($result['status']){
            if(is_null($result['info'])){
                return $this->apiReturnErr('指定帖子不存在');
            }
        }else{
            return $this->apiReturnErr('删除失败');
        }


        $can_delete = false;

        $post_info = $result['info'];
        $fid = $post_info['fid'];


        //查询评论信息
        $map = array(
            'tid' => $tid,
            'pid' => $pid,
            'id' => $id
        );
        $result = apiCall(ForumPostcommentApi::GET_INFO,array($map));

        if($result['status']) {
            $comment_info = $result['info'];
        }else{
            return $this->apiReturnErr('删除失败');
        }

        if(is_null($comment_info)){
            return $this->apiReturnErr('删除失败,指定评论不存在');
        }

        if($post_info['author_id']==$uid){
            //帖子主人可以删
            $can_delete = true;
        }else{
            if($comment_info['author_id']==$uid){
                //评论者可删除
                $can_delete = true;
            }
        }

        //验证用户权限
        $result = apiCall(ForumUserAdmingroupApi::POWER,array($uid));
        if($result['status']){
            $power = $result['info'];

            if(is_array($power)){
                if($power[ForumAdmingroupModel::ALLOW_DEL_POST] == 1 && ($power['fid'] == $fid || $power['fid'] == 0)){
                    $can_delete = true;
                }

            }
        }else{
            return $this -> apiReturnErr($result['info']);
        }


        if(!$can_delete){
            return $this->apiReturnErr('该用户没有删帖权限');
        }


        $map = array(
            'tid' => $tid,
            'pid' => $pid,
            'id' => $id
        );

        $result = apiCall(ForumPostcommentApi::DELETE,array($map));

        if($result['status']){

            if($result['info']<1){
                return $this->apiReturnErr('删除失败');
            }else{

                //统计帖子评论数量，为0需要设置
                $map = array(
                    'tid' => $tid,
                    'pid' => $pid,
                );
                $result = apiCall(ForumPostcommentApi::COUNT,array($map));
                if($result['status']){
                    if(!is_null($result['info']) && $result['info'] == 0){
                        //帖子是否评论为0
                        $map = array(
                            'pid' => $pid,
                            'tid' => $tid
                        );
                        $result = apiCall(ForumPostApi::SAVE,array($map,array('comment'=>0)));
                    }
                }

                return $this->apiReturnSuc('删除成功');
            }

        }else{
            return $this->apiReturnErr('删除失败');
        }
    }

    public function replyPost($pid,$tid,$author,$author_id,$comment){

        //取主题帖信息
        $fid = false;
        $map = array(
            'tid' => $tid,
        );
        $result = apiCall(ForumThreadApi::GET_INFO,array($map));
        if($result['status']){
            $fid =$result['info']['fid'];
        }else{
            return $this -> apiReturnErr($result['info']);
        }
        if($fid === false){
            return $this -> apiReturnErr("参数有误");
        }
        //验证用户权限
        $result = apiCall(ForumUserAdmingroupApi::POWER,array($author_id));
        if($result['status']){
            $power = $result['info'];
            if(is_array($power)){
                if($power[ForumAdmingroupModel::ALLOW_POST] == 0 && ($power['fid'] == $fid || $power['fid'] == 0)){
                    return $this -> apiReturnErr("无回帖权限");
                }
            }
        }else{
            return $this -> apiReturnErr($result['info']);
        }

        //查询帖子是否是1楼贴，不能回复
        $map = array(
            'pid' => $pid,
            'tid' => $tid
        );
        $result = apiCall(ForumPostApi::GET_INFO,array($map));

        if($result['status']){
            if(is_null($result['info'])){
                return $this->apiReturnErr("帖子不存在");
            }else{
                if($result['info']['position']==0){
                    return $this->apiReturnErr('不能评论主题贴');
                }
            }
        }else{
            return $this->apiReturnErr("获取帖子信息失败");
        }

        $useip = 0;
        if(!empty($_SERVER['REMOTE_ADDR'])){
            $useip = $_SERVER['REMOTE_ADDR'];
        }

        $entity = array(
            'tid' => $tid,
            'pid' => $pid,
            'author' => $author,
            'author_id' => $author_id,
            'dateline' => time(),
            'comment' => $comment,
            'useip' => ip2long($useip),
            'rpid' => 0,
        );

        $result = apiCall(ForumPostcommentApi::ADD,array($entity));

        if($result['status']){
            if($result['info']>0){

                //帖子是否评论为1
                $map = array(
                    'pid' => $pid,
                    'tid' => $tid
                );
                $result = apiCall(ForumPostApi::SAVE,array($map,array('comment'=>1)));

                return $this->apiReturnSuc('评论成功');

            }else{
                return $this->apiReturnErr('评论失败');
            }
        }else{
            return $this->apiReturnErr('评论失败');
        }
    }

    /**
     * 查询用户信息
     */
    private function getUserInfo($uid,&$arr){
        //$result = apiCall('Api/BbsUserCenter/userInfo',array($uid),'Domain');
        $result = apiCall(BbsMemberApi::GET_USER_INFO,array($uid));
        if($result['status']){
            $arr['user_info'] = $result['info'];
        }else{
            return $this->apiReturnErr('查询用户信息失败');
        }
    }

    /**
     * 查询附件
     */
    private function queryAttachment($tid,$pid,&$arr){

        //查询附件
        $map = array(
            'pid' => $pid,
            'tid' => $tid
        );
        $result = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,array('aid')));
        if($result['status']){
            $arr['img'] = array();
            foreach($result['info'] as $key=>$v){
                if($key >5)break;
                array_push($arr['img'],$v['aid']);
            }

        }

    }

    /**
     * 查询指定条数评论
     */
    private function queryComments($tid,$pid,$maxcomment,&$arr){

        if($arr['comment']==1){
            $arr['view_more'] = 0;
            $map = array(
                'tid' => $tid,
                'pid' => $pid,
            );
            $order['id'] = 'desc';
            $page = array('curpage'=>0,'size'=>$maxcomment);
            $result = apiCall(ForumPostcommentApi::QUERY_WITH_COUNT,array($map,$page,'id desc'));
            if($result['status']){
                if($result['info']['count']<=$maxcomment){
                    //不需要查看更多
                }else{
                    $arr['view_more'] = 1;
                }
                $arr['comment_num'] = $result['info']['count'];
                $arr['comments'] = $result['info']['list'];

                foreach($arr['comments'] as &$val){
                    //时间转换
                    $val['dateline_show'] = date("Y-m-d H:i:s",$val['dateline']);
                    //查询用户信息
                    $this->getUserInfo($val['author_id'],$val);
                }
            }else{
                return $this->apiReturnErr('获取'.$arr['pid'].'评论失败');
            }
        }

    }


    /**
     * 查看所有帖子，根据显示未显示分
     */
    public function queryAllPost2($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false){

        $query = $this->model->alias('p');
        // $join  = array('LEFT JOIN __FORUM_THREAD__ as t ON p.fid=t.fid');
        // $query = $query->join($join);
        $where = array();
        if(!is_null($map)) $query = $query->where($map);
        // if($display == 1){
        //     $where['_complex'] = array(
        //         'invisible' => 1,
        //         'modnewposts' => 0,
        //         '_logic' => 'or'
        //     );
        // }else{
        //     $where['_complex'] = array(
        //         'invisible' => 0,
        //         'modnewposts' => 1,
        //     );
        // }
        // $query = $query->where($where);

        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model
        //-> join($join)
        -> where($map)
        //-> where($where)
        -> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();
        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
    }


}